#!/usr/bin/python

#from gevent import monkey
#monkey.patch_all()
import os
import time
#from gevent import subprocess
#from gevent.socket as socket
import subprocess
import socket
#import telnetlib
import re
import threading
#import gevent.queue as Queue
#from gevent import spawn
#from gevent import sleep
from time import sleep

class spawn:
    def __init__(self, func, *args, **kargs):
        self.value = None
        self.func=func
        self.arg=args
        self.t=None
        self.kargs = kargs
        #self.q=Queue.Queue()
    def start(self):
        self.t=threading.Thread(target=self.f)
        self.t.start()

    def join(self):
        self.t.join()

    def f(self):
        #print "arg",self.arg,self.kargs
        d=self.func(*self.arg,**self.kargs)
        self.value = d

def get_net_traffic(t=1,dev="eth0"):
    rb1=0
    tb1=0
    rb2=0
    tb2=0
    start =time.time()
    fp=open("/proc/net/dev")
    try:
        line=fp.readline()
        while line:
            datas=line.split()
            if dev in datas[0]:
                rb1=int(datas[1])
                tb1=int(datas[9])
            line=fp.readline()
    finally:
        fp.close()

    sleep(t)

    fp=open("/proc/net/dev")
    try:
        line=fp.readline()
        while line:
            datas=line.split()
            if dev in datas[0]:
                rb2=int(datas[1])
                tb2=int(datas[9])
            line=fp.readline()
    finally:
        fp.close()

    end=time.time()
    rx=(rb2-rb1)/(end-start)/1024.0
    tx=(tb2-tb1)/(end-start)/1024.0

    return (rx,tx)

def get_cpu_usage(t=1):

    u1=0
    u2=0
    ua=0
    total1=0
    total2=0
    start=time.time()
    fp=open("/proc/stat")
    try:
        line=fp.readline()
        #print line
        d=line.split()
        if d[0] == "cpu":
            d.remove(d[0])
            #print d
            total1=sum([int(i) for i in d])
            idle=float(d[3])
            u1=total1-idle
    finally:
        fp.close()

    sleep(t)
    fp=open("/proc/stat")
    try:
        line=fp.readline()
        #print line
        d=line.split()
        if d[0] == "cpu":
            d.remove(d[0])
            #print d
            total2=sum([int(i) for i in d])
            idle=float(d[3])
            u2=total2-idle
    finally:
        fp.close()

    end = time.time()
    ua=(u2-u1)/(total2-total1) *100
    return ua

def get_mem_usage(t=1):

    fp=open("/proc/meminfo")
    total=1
    free=0
    try:
        line=fp.readline()
        while line:
            if "MemTotal:" in line:
                total = float(line.split()[1])
            if "MemFree:" in line:
                free = float(line.split()[1])
            line=fp.readline()
    finally:
        fp.close()

    return ((total-free)/total * 100)

def get_load(t=1):
    fp=open("/proc/loadavg")
    line=fp.readline()
    fp.close()
    return float(line.split()[0])

def get_opensips_user(vendor="all",type="all"):
    #print "vendor",vendor,"type",type
    def match_vendor(d,v):
        if v == "all":
            return True
        l=d.strip(" \r\n")
        aor=l.split()[1]
        aor_s=aor.split("_")
        if aor_s[0].lower() == v.lower():
            return True
        return False

    def match_type(d, t):
        if t == "all":
            return True
        l=d.strip(" \r\n")
        aor=l.split()[1]
        #aor_s=aor.split("_")
        if t == "phone":
            if "_A_" in aor or "_I_" in aor:
                return True
        elif t == "wifidisk":
            if "_A_" not in aor and "_I_" not in aor:
                return True
        return False

    p=subprocess.Popen("/opt/opensips/sbin/opensipsctl ul show", shell=True, stdout=subprocess.PIPE)
    #p.communicate()
    line = p.stdout.readline()
    count = 0
    while line:
        if "AOR::" in line:
            if match_vendor(line,vendor) and match_type(line,type.lower()):
                count+=1
        line=p.stdout.readline()
    p.wait()
    #p.close()
    return count

p=r"Total sessions: (\d+)"
p1=re.compile(p)

def get_turn_user(t=1):
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect(("127.0.0.1",5766))
    s.recv(512)
    s.send("pu\n")
    data=s.recv(100)
    s.send("quit\n")
    s.close()
    g=p1.search(data)
    return int(g.groups(0)[0])

def get_all(t=1,dev="eth0", vendor="all", type="all"):
    #t1=threading.Thread(target=get_cpu,args=(t,qcpu))
    t1=spawn(get_cpu_usage,t)
    t1.start()

    #t2=threading.Thread(target=get_net,args=(t,dev,qnet))
    t2=spawn(get_net_traffic,t,dev)
    t2.start()


    t3=spawn(get_opensips_user,vendor,type)
    t3.start()
    
    turn=get_turn_user()
    t4=spawn(get_turn_user)
    t4.start()

    t5=spawn(get_mem_usage)
    t5.start()

    #mem=get_mem_usage()
    #load=get_load()
    t6=spawn(get_load)
    t6.start()

    for tt in [t1,t2,t3,t4,t5,t6]:
        tt.join()

    cpu=t1.value
    rx,tx=t2.value
    u=t3.value
    turn=t4.value
    mem=t5.value
    load=t6.value

    return (cpu,mem,rx,tx,u,turn,load)

def get_user_status():
    p=subprocess.Popen("/opt/opensips/sbin/opensipsctl ul show", shell=True, stdout=subprocess.PIPE)
    line = p.stdout.readline()
    u={}
    while line:
        if "AOR::" in line:
            line = line.strip(" \r\n")
            id=line.split()[1]
            a=id.split("_")
            vendor=a[0]
            if not u.has_key(vendor):
                u[vendor]=dict(num = 0,
                        phone = 0,
                        dev = 0)
            d=u[vendor]

            d["num"] += 1
            if "_A_" in id or "_I_" in id:
                d["phone"] += 1
            else:
                d["dev"] += 1


        line = p.stdout.readline()
    p.wait()
    return u
if __name__ == "__main__":
    #for i in range(100):
        #print get_net_traffic(3)
        #print get_cpu_usage()
        #print get_cpu_usage(),get_mem_usage(),get_net_traffic(),get_load(),get_opensips_user(),get_turn_user()
        #print get_turn_user()
    #    print get_all(0.5)
    #    sleep(1)
    #cpu,mem,(rx,tx),load,turn=get_cpu_usage(),get_mem_usage(),get_net_traffic(),get_load(),get_turn_user()
    #print cpu,mem,rx,tx,load,turn
    a=get_user_status()
    print a.keys()
    print a
